package zy.service.stock.allocate.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zy.dao.approve.ApproveRecordDAO;
import zy.dao.base.product.ProductDAO;
import zy.dao.base.size.SizeDAO;
import zy.dao.stock.allocate.AllocateDAO;
import zy.dao.stock.data.DataDAO;
import zy.dao.stock.useable.UseableDAO;
import zy.dao.sys.print.PrintDAO;
import zy.dto.common.ProductDto;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.approve.T_Approve_Record;
import zy.entity.base.product.T_Base_Barcode;
import zy.entity.base.product.T_Base_Product;
import zy.entity.base.size.T_Base_Size;
import zy.entity.base.size.T_Base_SizeList;
import zy.entity.stock.T_Stock_Import;
import zy.entity.stock.allocate.T_Stock_Allocate;
import zy.entity.stock.allocate.T_Stock_AllocateList;
import zy.entity.stock.data.T_Stock_DataBill;
import zy.entity.sys.set.T_Sys_Set;
import zy.entity.sys.user.T_Sys_User;
import zy.service.stock.allocate.AllocateService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import zy.vo.common.SizeHorizontalVO;
import zy.vo.stock.AllocateVO;

@Service
public class AllocateServiceImpl implements AllocateService{
	@Resource
	private AllocateDAO allocateDAO;
	
	@Resource
	private SizeDAO sizeDAO;
	
	@Resource
	private ApproveRecordDAO approveRecordDAO;
	
	@Resource
	private DataDAO dataDAO;
	
	@Resource
	private ProductDAO productDAO;
	
	@Resource
	private PrintDAO printDAO;
	
	@Resource
	private UseableDAO useableDAO;

	@Override
	public PageData<T_Stock_Allocate> page(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = allocateDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Stock_Allocate> list = allocateDAO.list(params);
		PageData<T_Stock_Allocate> pageData = new PageData<T_Stock_Allocate>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}

	@Override
	public T_Stock_Allocate load(Integer ac_id) {
		T_Stock_Allocate allocate = allocateDAO.load(ac_id);
		if(allocate != null){
			T_Approve_Record approve_Record = approveRecordDAO.load(allocate.getAc_number(), allocate.getCompanyid());
			if(approve_Record != null){
				allocate.setAr_describe(approve_Record.getAr_describe());
			}
		}
		return allocate;
	}

	@Override
	public List<T_Stock_AllocateList> detail_list(Map<String, Object> params) {
		return allocateDAO.detail_list(params);
	}
	
	@Override
	public List<T_Stock_AllocateList> detail_sum(Map<String, Object> params) {
		return allocateDAO.detail_sum(params);
	}
	
	@Override
	public Map<String, Object> detail_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = allocateDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}
	
	@Override
	public Map<String, Object> detail_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = allocateDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "acl_pd_code,acl_cr_code,acl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Stock_AllocateList> temps = allocateDAO.detail_list(params);
		return AllocateVO.getJsonSizeData(sizeGroupList, temps);
	}
	
	@Override
	public List<T_Stock_AllocateList> temp_list(Map<String, Object> params) {
		return allocateDAO.temp_list(params);
	}

	@Override
	public List<T_Stock_AllocateList> temp_sum(Map<String, Object> params) {
		return allocateDAO.temp_sum(params);
	}

	@Override
	public Map<String, Object> temp_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = allocateDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}

	@Override
	public Map<String, Object> temp_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = allocateDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "acl_pd_code,acl_cr_code,acl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Stock_AllocateList> temps = allocateDAO.temp_list(params);
		return AllocateVO.getJsonSizeData(sizeGroupList, temps);
	}
	
	@Override
	@Transactional
	public Map<String, Object> temp_save_bybarcode(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String barcode = (String)params.get("barcode");
		Integer amount = (Integer)params.get("amount");
		T_Sys_User user = (T_Sys_User)params.get("user");
		T_Base_Barcode base_Barcode = productDAO.loadBarcode(barcode, user.getCompanyid());
		if(base_Barcode == null){
			resultMap.put("result", 3);//条码不存在
			return resultMap;
		}
		T_Stock_AllocateList temp = allocateDAO.temp_loadBySubCode(base_Barcode.getBc_subcode(), user.getUs_id(), user.getCompanyid());
		if (temp != null) {//临时表存在则直接更新数量
			temp.setAcl_amount(temp.getAcl_amount()+amount);
			allocateDAO.temp_update(temp);
			resultMap.put("result", 1);//update
			resultMap.put("temp", temp);
			return resultMap;
		}
		T_Base_Product base_Product = allocateDAO.load_product(base_Barcode.getBc_pd_code(), user.getCompanyid());
		Double unitPrice = allocateDAO.temp_queryUnitPrice(base_Barcode.getBc_pd_code(), user.getUs_id(), user.getCompanyid());;
		if(unitPrice == null){
			unitPrice = base_Product.getPd_cost_price();
		}
		temp = new T_Stock_AllocateList();
		temp.setAcl_pd_code(base_Barcode.getBc_pd_code());
		temp.setAcl_cr_code(base_Barcode.getBc_color());
		temp.setAcl_sz_code(base_Barcode.getBc_size());
		temp.setAcl_szg_code(base_Product.getPd_szg_code());
		temp.setAcl_br_code(base_Barcode.getBc_bra());
		temp.setAcl_sub_code(temp.getAcl_pd_code()+temp.getAcl_cr_code()+temp.getAcl_sz_code()+temp.getAcl_br_code());
		temp.setAcl_amount(amount);
		temp.setAcl_unitprice(unitPrice);
		temp.setAcl_remark("");
		temp.setAcl_us_id(user.getUs_id());
		temp.setCompanyid(user.getCompanyid());
		allocateDAO.temp_save(temp);
		temp.setPd_no(base_Product.getPd_no());
		temp.setPd_name(base_Product.getPd_name());
		temp.setPd_unit(base_Product.getPd_unit());
		temp.setBd_name(base_Product.getPd_bd_name());
		temp.setTp_name(base_Product.getPd_tp_name());
		temp.setCr_name(base_Barcode.getBc_colorname());
		temp.setSz_name(base_Barcode.getBc_sizename());
		temp.setBr_name(base_Barcode.getBc_braname());
		resultMap.put("result", 2);//add
		resultMap.put("temp", temp);
		return resultMap;
	}
	
	@Override
	public PageData<T_Base_Product> page_product(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = allocateDAO.count_product(param);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		
		List<T_Base_Product> list = allocateDAO.list_product(param);
		PageData<T_Base_Product> pageData = new PageData<T_Base_Product>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> temp_loadproduct(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		T_Sys_Set sysSet = (T_Sys_Set)params.get(CommonUtil.KEY_SYSSET);
		Integer us_id = (Integer)params.get("us_id");
		String pd_code = (String)params.get("pd_code");
		String dp_code = (String)params.get("dp_code");
		String exist = (String)params.get("exist");
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		T_Base_Product base_Product = allocateDAO.load_product(pd_code, companyid);
		Map<String, Object> product = new HashMap<String, Object>();
		product.put("pd_id", base_Product.getPd_id());
		product.put("pd_code", base_Product.getPd_code());
		product.put("pd_no", base_Product.getPd_no());
		product.put("pd_name", base_Product.getPd_name());
		product.put("pd_szg_code", base_Product.getPd_szg_code());
		product.put("pd_unit", base_Product.getPd_unit());
		product.put("pd_year", base_Product.getPd_year());
		product.put("pd_season", base_Product.getPd_season());
		product.put("pd_sell_price", base_Product.getPd_sell_price());
		product.put("pdm_buy_price", base_Product.getPd_buy_price());
		product.put("pdm_cost_price", base_Product.getPd_cost_price());
		product.put("pd_bd_name", base_Product.getPd_bd_name());
		product.put("pd_tp_name", base_Product.getPd_tp_name());
		product.put("pdm_img_path", StringUtil.trimString(base_Product.getPdm_img_path()));
		Double unitPrice = null;
		if("1".equals(exist)){//已经录入从临时表中查询单价
			unitPrice = allocateDAO.temp_queryUnitPrice(pd_code, us_id, companyid);
			product.put("temp_unitPrice", StringUtil.trimString(unitPrice));
		}
		if(unitPrice == null){
			unitPrice = base_Product.getPd_cost_price();
		}
		product.put("unitPrice", unitPrice);
		resultMap.put("product", product);
		params.put("szg_code", base_Product.getPd_szg_code());
		Map<String, Object> productMap = allocateDAO.load_product_size(params);
		List<T_Base_Size> sizes=(List<T_Base_Size>)productMap.get("sizes");
		List<ProductDto> inputs=(List<ProductDto>)productMap.get("inputs");
		List<ProductDto> temps=(List<ProductDto>)productMap.get("temps");
		List<ProductDto> stocks=(List<ProductDto>)productMap.get("stocks");
		Map<String,Object> usableStockMap = null;
		if (sysSet.getSt_useable() != null && sysSet.getSt_useable().intValue() == 1) {
			usableStockMap = useableDAO.loadUseableStock(pd_code, dp_code, companyid);
		}
		resultMap.putAll(SizeHorizontalVO.buildJsonProductInput(pd_code, sizes, inputs, stocks, temps, usableStockMap));
		return resultMap;
	}
	
	@Override
	@Transactional
	public void temp_save(Map<String, Object> params) {
		List<T_Stock_AllocateList> temps = (List<T_Stock_AllocateList>)params.get("temps");
		T_Sys_User user = (T_Sys_User)params.get("user");
		Object pd_code = params.get("pd_code");
		Object unitPrice = params.get("unitPrice");
		if (temps != null && temps.size() > 0) {
			List<T_Stock_AllocateList> temps_add = new ArrayList<T_Stock_AllocateList>();
			List<T_Stock_AllocateList> temps_update = new ArrayList<T_Stock_AllocateList>();
			List<T_Stock_AllocateList> temps_del = new ArrayList<T_Stock_AllocateList>();
			for (T_Stock_AllocateList item : temps) {
				if ("add".equals(item.getOperate_type())){
					if (item.getAcl_amount() > 0) {
						temps_add.add(item);
					}
				}else if("update".equals(item.getOperate_type())){
					if(!item.getAcl_amount().equals(0)){
						temps_update.add(item);
					}else {
						temps_del.add(item);
					}
				}
			}
			if (temps_add.size() > 0) {
				allocateDAO.temp_save(temps_add);
			}
			if (temps_update.size() > 0) {
				allocateDAO.temp_update(temps_update);
			}
			if (temps_del.size() > 0) {
				allocateDAO.temp_del(temps_del);
			}
		}
		if (StringUtil.isNotEmpty(pd_code) && StringUtil.isNotEmpty(unitPrice)) {
			allocateDAO.temp_updateprice(pd_code.toString(), Double.parseDouble(unitPrice.toString()), user.getUs_id(), user.getCompanyid());
		}
	}
	
	@Override
	@Transactional
	public void temp_import(Map<String, Object> params) {
		List<String[]> datas = (List<String[]>)params.get("datas");
		T_Sys_User user = (T_Sys_User)params.get("user");
		List<String> barcodes = new ArrayList<String>();
		Map<String, Integer> data_amount = new HashMap<String, Integer>();
		for (String[] data : datas) {
			barcodes.add(data[0]);
			data_amount.put(data[0], Integer.parseInt(data[1]));
		}
		List<T_Stock_Import> imports = allocateDAO.temp_listByImport(barcodes, user.getCompanyid());
		if (imports == null || imports.size() == 0) {
			throw new RuntimeException("无数据可导入");
		}
		Map<String, Double> unitPriceMap = new HashMap<String, Double>();
		Map<String, T_Stock_AllocateList> tempsMap = new HashMap<String, T_Stock_AllocateList>();
		List<T_Stock_AllocateList> temps = allocateDAO.temp_list_forimport(user.getUs_id(), user.getCompanyid());
		for (T_Stock_AllocateList temp : temps) {
			if(!unitPriceMap.containsKey(temp.getAcl_pd_code())){
				unitPriceMap.put(temp.getAcl_pd_code(), temp.getAcl_unitprice());
			}
			tempsMap.put(temp.getAcl_sub_code(), temp);
		}
		List<T_Stock_AllocateList> temps_add = new ArrayList<T_Stock_AllocateList>();
		List<T_Stock_AllocateList> temps_update = new ArrayList<T_Stock_AllocateList>();
		for (T_Stock_Import item : imports) {
			if(tempsMap.containsKey(item.getBc_subcode())){//临时表已存在，更新数量
				T_Stock_AllocateList temp = tempsMap.get(item.getBc_subcode());
				temp.setAcl_amount(temp.getAcl_amount()+data_amount.get(item.getBc_barcode()));
				temps_update.add(temp);
			}else {//临时表不存在，新增数据
				T_Stock_AllocateList temp = new T_Stock_AllocateList();
				temp.setAcl_pd_code(item.getBc_pd_code());
				temp.setAcl_sub_code(item.getBc_subcode());
				temp.setAcl_sz_code(item.getBc_size());
				temp.setAcl_szg_code(item.getPd_szg_code());
				temp.setAcl_cr_code(item.getBc_color());
				temp.setAcl_br_code(item.getBc_bra());
				temp.setAcl_amount(data_amount.get(item.getBc_barcode()));
				if(unitPriceMap.containsKey(item.getBc_pd_code())){//临时表已存在此货号，则使用临时表价格
					temp.setAcl_unitprice(unitPriceMap.get(item.getBc_pd_code()));
				}else{
					temp.setAcl_unitprice(item.getUnit_price());
				}
				temp.setAcl_remark("");
				temp.setAcl_us_id(user.getUs_id());
				temp.setCompanyid(user.getCompanyid());
				temps_add.add(temp);
			}
		}
		if (temps_add.size() > 0) {
			allocateDAO.temp_save(temps_add);
		}
		if (temps_update.size() > 0) {
			allocateDAO.temp_updateById(temps_update);
		}
	}
	
	@Override
	@Transactional
	public void temp_import_draft(Map<String, Object> params) {
		String ac_number = (String)params.get("ac_number");
		T_Sys_User user = (T_Sys_User)params.get("user");
		List<T_Stock_AllocateList> details = allocateDAO.detail_list_forsavetemp(ac_number,user.getCompanyid());
		if (details == null || details.size() == 0) {
			throw new RuntimeException("草稿不存在");
		}
		for(T_Stock_AllocateList item:details){
			item.setAcl_us_id(user.getUs_id());
		}
		allocateDAO.temp_clear(user.getUs_id(), user.getCompanyid());
		allocateDAO.temp_save(details);
		allocateDAO.del(ac_number, user.getCompanyid());
	}
	
	@Override
	@Transactional
	public void temp_updateAmount(T_Stock_AllocateList temp) {
		allocateDAO.temp_update(temp);
	}
	
	@Override
	@Transactional
	public void temp_updatePrice(T_Stock_AllocateList temp) {
		allocateDAO.temp_updateprice(temp.getAcl_pd_code(), temp.getAcl_unitprice(), 
				temp.getAcl_us_id(), temp.getCompanyid());
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkById(T_Stock_AllocateList temp) {
		allocateDAO.temp_updateRemarkById(temp);
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkByPdCode(T_Stock_AllocateList temp) {
		allocateDAO.temp_updateRemarkByPdCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_del(Integer acl_id) {
		allocateDAO.temp_del(acl_id);
	}
	
	@Override
	@Transactional
	public void temp_delByPiCode(T_Stock_AllocateList temp) {
		if (temp.getCompanyid() == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if (temp.getAcl_us_id() == null) {
			throw new IllegalArgumentException("参数us_id不能为null");
		}
		allocateDAO.temp_delByPiCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_clear(Integer us_id,Integer companyid) {
		allocateDAO.temp_clear(us_id, companyid);;
	}
	
	@Override
	@Transactional
	public void save(T_Stock_Allocate allocate, T_Sys_User user) {
		if(allocate == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(allocate.getAc_outdp_code())){
			throw new IllegalArgumentException("发货仓库不能为空");
		}
		if(StringUtil.isEmpty(allocate.getAc_indp_code())){
			throw new IllegalArgumentException("收货仓库不能为空");
		}
		if(StringUtil.isEmpty(allocate.getAc_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		allocate.setCompanyid(user.getCompanyid());
		allocate.setAc_us_id(user.getUs_id());
		allocate.setAc_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		allocate.setAc_sysdate(DateUtil.getCurrentTime());
		//1.查临时表
		List<T_Stock_AllocateList> temps = allocateDAO.temp_list_forsave(user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("单据已保存，请勿重复提交");
		}
		//2.保存单据
		int ac_amount = 0;
		double ac_money = 0d;
		for (T_Stock_AllocateList temp : temps) {
			ac_amount += temp.getAcl_amount();
			ac_money += temp.getAcl_amount() * temp.getAcl_unitprice();
		}
		allocate.setAc_amount(ac_amount);
		allocate.setAc_money(ac_money);
		allocateDAO.save(allocate, temps);
		//3.删除临时表
		allocateDAO.temp_clear(user.getUs_id(), user.getCompanyid());
	}
	
	@Override
	@Transactional
	public void update(T_Stock_Allocate allocate, T_Sys_User user) {
		if(allocate == null){
			throw new IllegalArgumentException("参数不能为null");
		}
		if(StringUtil.isEmpty(allocate.getAc_outdp_code())){
			throw new IllegalArgumentException("发货仓库不能为空");
		}
		if(StringUtil.isEmpty(allocate.getAc_indp_code())){
			throw new IllegalArgumentException("收货仓库不能为空");
		}
		if(StringUtil.isEmpty(allocate.getAc_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		allocate.setCompanyid(user.getCompanyid());
		allocate.setAc_us_id(user.getUs_id());
		allocate.setAc_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		allocate.setAc_sysdate(DateUtil.getCurrentTime());
		
		//1.1查临时表
		List<T_Stock_AllocateList> temps = allocateDAO.temp_list_forsave(user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("单据已保存，请勿重复提交");
		}
		
		//1.2验证单据
		T_Stock_Allocate oldaAllocate = allocateDAO.check(allocate.getAc_number(), user.getCompanyid());
		if (oldaAllocate == null || !CommonUtil.AR_STATE_FAIL.equals(oldaAllocate.getAc_ar_state())) {
			throw new RuntimeException("单据已修改，请勿重复提交");
		}
		//1.3删除子表
		allocateDAO.deleteList(allocate.getAc_number(), user.getCompanyid());
		//2.保存主表
		int ac_amount = 0;
		double ac_money = 0d;
		for (T_Stock_AllocateList temp : temps) {
			ac_amount += temp.getAcl_amount();
			ac_money += temp.getAcl_amount() * temp.getAcl_unitprice();
		}
		allocate.setAc_amount(ac_amount);
		allocate.setAc_money(ac_money);
		allocateDAO.update(allocate, temps);
		//3.删除临时表
		allocateDAO.temp_clear(user.getUs_id(), user.getCompanyid());
	}
	
	@Override
	@Transactional
	public T_Stock_Allocate approve(String number, T_Approve_Record record, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Stock_Allocate allocate = allocateDAO.check(number, user.getCompanyid());
		if(allocate == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(allocate.getAc_ar_state())){
			throw new RuntimeException("单据已经审核");
		}
		//1.更新单据审核状态
		allocate.setAc_ar_state(record.getAr_state());
		allocate.setAc_ar_date(DateUtil.getCurrentTime());
		allocateDAO.updateApprove(allocate);
		//2.保存审核记录表
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_stock_allocate");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		if(!CommonUtil.AR_STATE_APPROVED.equals(allocate.getAc_ar_state())){//审核不通过，则直接返回
			return allocate;
		}
		//3.审核通过,更新库存
		List<T_Stock_DataBill> stocks_out = allocateDAO.listStock(number, allocate.getAc_outdp_code(), user.getCompanyid());
		List<T_Stock_DataBill> stocks_in = allocateDAO.listStock(number, allocate.getAc_indp_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks_out) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allocate.getAc_outdp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(-stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() - stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		for (T_Stock_DataBill stock : stocks_in) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allocate.getAc_indp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() + stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		return allocate;
	}
	
	@Override
	@Transactional
	public T_Stock_Allocate reverse(String number, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Stock_Allocate allocate = allocateDAO.check(number, user.getCompanyid());
		if(allocate == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_APPROVED.equals(allocate.getAc_ar_state())){
			throw new RuntimeException("单据未审核或审核未通过");
		}
		//1.更新单据审核状态
		allocate.setAc_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		allocate.setAc_ar_date(DateUtil.getCurrentTime());
		allocateDAO.updateApprove(allocate);
		//2.保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_REVERSE_APPROVE);
		record.setAr_describe(user.getUs_name()+"反审核单据");
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_stock_allocate");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		//3更新库存
		List<T_Stock_DataBill> stocks_out = allocateDAO.listStock(number, allocate.getAc_outdp_code(), user.getCompanyid());
		List<T_Stock_DataBill> stocks_in = allocateDAO.listStock(number, allocate.getAc_indp_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks_out) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allocate.getAc_outdp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() + stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		for (T_Stock_DataBill stock : stocks_in) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allocate.getAc_indp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(-stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() - stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		return allocate;
	}
	
	@Override
	@Transactional
	public void initUpdate(String number, Integer us_id, Integer companyid) {
		List<T_Stock_AllocateList> details = allocateDAO.detail_list_forsavetemp(number,companyid);
		for(T_Stock_AllocateList item:details){
			item.setAcl_us_id(us_id);
		}
		allocateDAO.temp_clear(us_id, companyid);
		allocateDAO.temp_save(details);
	}

	@Override
	@Transactional
	public void del(String number, Integer companyid) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Stock_Allocate allocate = allocateDAO.check(number, companyid);
		if(allocate == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(allocate.getAc_ar_state()) && !CommonUtil.AR_STATE_FAIL.equals(allocate.getAc_ar_state())){
			throw new RuntimeException("单据已审核通过不能删除！");
		}
		allocateDAO.del(number, companyid);
	}
	
	@Override
	public Map<String, Object> loadPrintData(String number, Integer sp_id, Integer displayMode, T_Sys_User user) {
		Map<String, Object> resultMap = printDAO.loadPrint4Bill(sp_id);
		T_Stock_Allocate allocate = allocateDAO.load(number,user.getCompanyid());
		List<T_Stock_AllocateList> allocateList = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("acl_number", number);
		params.put("companyid", user.getCompanyid());
		if(displayMode.intValue() == 2){//汇总模式
			allocateList = allocateDAO.detail_sum(params);
		}else {
			allocateList = allocateDAO.detail_list_print(params);
		}
		resultMap.put("allocate", allocate);
		resultMap.put("allocateList", allocateList);
		resultMap.put("approveRecord", approveRecordDAO.load(number,user.getCompanyid()));
		if(displayMode.intValue() == 1){//尺码模式查询
			List<String> szgCodes = new ArrayList<String>();
			for (T_Stock_AllocateList item : allocateList) {
				if(!szgCodes.contains(item.getAcl_szg_code())){
					szgCodes.add(item.getAcl_szg_code());
				}
			}
			List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, user.getCompanyid());
			resultMap.put("sizeGroupList", sizeGroupList);
		}
		return resultMap;
	}
	
}
